package org.example.controller;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import org.example.domain.CarClient;
import org.example.service.CarClientService;
import org.example.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.HashMap;

/**
 * @author : Guosir
 * @date : 2024-06-29 10:31
 * @description :
 **/
@RestController
@RequestMapping("CarLogin")
public class CarLoginController {

    @Autowired
    CarClientService carClientService;


    @RequestMapping("login")
    public Result login(@RequestBody(required = false) CarClient carClient){
        CarClient dbCarClient =   carClientService.getOne(carClient.getClientName());
        if(dbCarClient==null){
            return Result.fail("用户名不正确！！！！");
        }
        String clientPassword = carClient.getClientPassword();
        String dbCarClientClientPassword = dbCarClient.getClientPassword();
        String salt = "qwer";
        String md5Hex = DigestUtil.md5Hex(clientPassword + salt);
        if(!md5Hex.equals(dbCarClientClientPassword)){
            return Result.fail("密码不正确！！！");
        }
        String token = JWT.create()
                .setPayload("clientName", dbCarClient.getClientName())
                .setPayload("password", dbCarClient.getClientPassword())
                .setPayload("clientId", dbCarClient.getClientId())
                .setSigner(JWTSignerUtil.none())
                .sign();
        HashMap<String, Object> map = new HashMap<>();
        map.put("clientId",dbCarClient.getClientId());
        map.put("clientName",dbCarClient.getClientName());
        map.put("password", dbCarClient.getClientPassword());
        map.put("token",token);
        return Result.success(map);
    }



    @PostConstruct
    public void initPWD(){
        String salt = "qwer";
        String pwd = "123456";
        String md5Hex = DigestUtil.md5Hex(pwd + salt);
        System.err.println("客户密码："+md5Hex);
    }




}
